#include <zemb/BaseType.h>
#include <zemb/Tracer.h>
#include <zemb/ArgUtil.h>
#include <zemb/Socket.h>
#include <zemb/Thread.h>

using namespace zemb;

#define SERVER_IP	"127.0.0.1" /* 定义服务器地址 */
#define SERVER_PORT	(8000)		/* 定义服务器端口 */
#define CLIENT_PORT (7999)

class MyUdpServer : public UdpServer{
public:
	bool onNewDatagram(UdpSocket& udpSocket, char * data, int len)
	{
		std::string peerAddr;
		uint16 peerPort;
		/* 获取对端连接信息 */
		udpSocket.getConnection(peerAddr, peerPort);
		TRACE_YELLOW("udp server recv cli: %s:%d",CSTR(peerAddr),peerPort);
		TRACE_YELLOW("udp server recv msg: %s",data);
		
		/* 回复客户端 */
		char buf[]="hello, i am server!";
		udpSocket.sendData(buf,sizeof(buf),1000);
		TRACE_YELLOW("udp server send msg: %s",buf);
		Thread::msleep(1000);
		/* 继续接收新数据 */
		return true;
	}
};

void testUdp(void)
{
	TRACE_INFO("udp test start >>>>>>");
	/* 创建一个线程给服务器,模拟服务器进程 */
	Thread serThread;
	MyUdpServer server;
    if(!server.setup(SERVER_IP,SERVER_PORT))
    {
        TRACE_ERR("init UDP server failed.");
		return;
    }

	/* 启动服务线程 */
    serThread.start(server);
	Thread::msleep(1000); 
    TRACE_REL("udp server ready.");

	UdpSocket client;
	if(!client.open("",CLIENT_PORT))
	{
		TRACE_ERR("udp client open error!");
	}
    if(!client.setConnection(SERVER_IP,SERVER_PORT))
    {
		TRACE_ERR("connect udp server error!");
	}

	/* 发送消息给服务器 */
	char sendBuf[]="hello, i am client!";
	if(client.sendData(sendBuf, sizeof(sendBuf),-1)>0)
	{
		TRACE_CYAN("udp client send: %s",sendBuf);
	}
	else
	{
		TRACE_ERR("udp client send error!");
	}

	/* 读取服务端回复消息 */
    char buf[64]={0};
    int rc=client.recvData(buf, sizeof(buf), 10000000);
    if (rc>0)
    {
        TRACE_CYAN("udp client recv:[%s]",buf);
    }
	else
	{
		TRACE_ERR("udp client recv error!");
	}

    serThread.stop();

	TRACE_INFO("udp test finished <<<<<<");
}
